package util

import (
	"crypto/tls"
	"fmt"

	gomail "gopkg.in/mail.v2"

	"net/smtp"

	"github.com/jordan-wright/email"
	"github.com/spf13/viper"

	"strconv"
)

type Email struct {
	Smtp     string
	Port     string
	Authcode string
	From     string
}

func main() {
	to := []string{"jsl_668@163.com", "jsl_668@126.com"}
	re, err := sendMail("", to, "测试邮件title标题", "测试邮件content内容，啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦......", 1)
	fmt.Println("----------------------------------------------------------------")
	fmt.Println(re)
	fmt.Println("----------------------------------------------------------------")
	fmt.Println(err)
	fmt.Println("----------------------------------------------------------------")
}

// 发送邮件
func sendMail(from string, to []string, title string, content string, last int) (string, error) {

	if len(to) < 1 {
		fmt.Println("无接收者")
	}
	EMConf, bol := mailConf(from)
	if bol == false {
		fmt.Println("配置文件错误")
	}
	var re string
	var err error
	if last == 1 {

		re, err = sendMailOne(EMConf, to, title, content)
	} else {

		re, err = send(EMConf, to, title, content)
	}

	if err != nil {
		fmt.Println(err.Error())
	}
	return re, err
}

// 邮件配置
func mailConf(from string) (*Email, bool) {

	vipe := viper.New()
	vipe.AddConfigPath("./../conf")
	vipe.SetConfigName("config")
	vipe.SetConfigType("yaml")

	if err := vipe.ReadInConfig(); err != nil {
		fmt.Println("找不到配置文件或配置错误")
	}
	mail := &Email{}

	smtpStr := vipe.GetString("mail.smtp")
	if smtpStr == "" {
		smtpStr = "smtp.qq.com"
	}
	mail.Smtp = smtpStr

	port := vipe.GetString("mail.port")
	if port == "" {
		port = "465"
	}
	mail.Port = port

	if from == "" {
		from = vipe.GetString("mail.from")
	}
	mail.From = from

	authcode := vipe.GetString("mail.authcode")
	if authcode == "" {
		authcode = "hkcgpomycbcsbadb"
	}
	mail.Authcode = authcode
	vipe = nil
	return mail, true
}

// 发送多发(单发接收者为1)
func send(em *Email, to []string, title string, content string) (string, error) {

	e := email.NewEmail()
	e.To = to
	e.From = em.From
	e.Subject = title
	e.HTML = []byte(content)

	auth := smtp.PlainAuth("", em.From, em.Authcode, em.Smtp)
	var err error
	err = e.SendWithTLS(em.Smtp+":"+em.Port, auth, &tls.Config{ServerName: em.Smtp})
	if err != nil {
		return "", err
	}
	return "success", nil
}

// 邮件单位
func sendMailOne(EMConf *Email, to []string, title string, content string) (string, error) {

	port, _ := strconv.Atoi(EMConf.Port)

	m := gomail.NewMessage()
	m.SetHeader("From", EMConf.From)
	m.SetHeader("To", to[0])
	m.SetHeader("Subject", title)
	m.SetBody("text/plain", content)
	d := gomail.NewDialer(EMConf.Smtp, port, EMConf.From, EMConf.Authcode)
	d.TLSConfig = &tls.Config{InsecureSkipVerify: true}
	if err := d.DialAndSend(m); err != nil {
		return "", err
	}
	return "success2", nil
}
